import { hundreds } from "../../static/js/loveData";
import dayjs from "dayjs";

const defaultAvatarUrl =
  "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0";

// 获取应用实例
const app = getApp();

// 初始化数据库
const db = wx.cloud.database();
const uimg = db.collection("uimg");
const message = db.collection("message");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    theme: "",
    avatarUrl: "",
    nickname: "",
    userInfoMask: false,
    openid: "",
    unionid: "",
    hasUser: false,
    hasUserInfo: false,

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,
  },

  enterInto() {
    const that = this;
    wx.showLoading({
      title: "登录中...",
      mask: true,
    });
    // that.getOpenid();
    app.getOpenidSuccess(() => {
      that.getUserData(app.globalData.openid, app.globalData.unionid)
    })
  },

  // 获取用户 openid 和 unionid
  getOpenid() {
    let that = this;
    wx.cloud.callFunction({
      name: "get",
      success: (res) => {
        var openid = res.result.openid;
        var unionid = res.result.unionid;
        that.setData({
          openid,
          unionid
        });
        that.getUserData(openid, unionid);
      },
      fail: (err) => {
        wx.showModal({
          title: '错误提示',
          content: '获取信息出现错误，请重试',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) { }
          }
        })
      },
      complete: () => { },
    });
  },

  // 判断是否有该用户
  getUserData(openid, unionid) {
    const that = this;
    uimg.where({
      _openid: openid,
      // unionid
    }).get({
      success: (res) => {
        let userList = res.data;
        if (userList.length == 0) {
          uimg.add({
            data: {
              unionid,
              avatarUrl: defaultAvatarUrl,
              nickname: "微信用户",
              love_time: "",
              love_word: [],
              mySwiper: [],
              memorial: [],
              o_openid: "",
              hundred: hundreds,
              score: [],
              heartbeat_value: 50,
              join_time: dayjs(new Date()).format("YYYY/MM/DD HH:mm:ss")
            },
            success: (res) => {
              that.setData({
                userInfoMask: true,
                avatarUrl: defaultAvatarUrl,
                nickname: "微信用户",
              });
            },
            fail: () => {
              wx.showToast({
                title: "请重新进入",
                icon: "none",
              });
            },
            complete: () => {
              wx.hideLoading();
            },
          });
          message.add({
            data: {
              myMsg: [],
              avatarUrl: defaultAvatarUrl,
              nickname: '微信用户',
            },
            success: () => { },
            fail: () => { },
            complete: () => { },
          });
        } else {
          wx.hideLoading();
          that.setData({
            hasUserInfo: true,
            avatarUrl: userList[0].avatarUrl,
            nickname: userList[0].nickname,
          });
          wx.setStorageSync("unionid", userList[0].unionid);

          if (userList[0].o_openid) {
            wx.setStorageSync("o_openid", userList[0].o_openid);
          } else {
            wx.setStorageSync("o_openid", "");
          }

          that.timer(openid, userList[0].avatarUrl, userList[0].nickname);
        }
      },
    });


  },

  // 设置openid，进去空间
  timer(openid, avatarUrl, nickname) {
    wx.setStorageSync("openid", openid);
    wx.setStorageSync("avatarUrl", avatarUrl);
    wx.setStorageSync("nickname", nickname);

    // message.where({ _openid: openid }).get({
    //   success: (res) => {
    //     if (res.data.length == 0) {
    //       message.add({
    //         data: {
    //           myMsg: [],
    //           avatarUrl: wx.getStorageSync("avatarUrl") || defaultAvatarUrl,
    //           nickname: wx.getStorageSync("nickname") || '微信用户',
    //         },
    //         success: () => { },
    //         fail: () => { },
    //         complete: () => { },
    //       });
    //     }
    //   }
    // });

    setTimeout(() => {
      wx.reLaunch({
        url: "/pages/index/index",
      });
      wx.showToast({
        title: "登录成功",
        icon: "success",
      });
    }, 2000);
  },

  closeUserInfoMask(e) {
    let { openid, avatarUrl, nickname } = this.data;

    this.setData({
      userInfoMask: false,
      hasUserInfo: true,
    });
    this.timer(openid, avatarUrl, nickname);
  },

  setUser(e) {
    const { openid } = this.data;
    this.setData({
      hasUserInfo: e.detail.hasUserInfo,
      avatarUrl: e.detail.avatarUrl,
      nickname: e.detail.nickname,
      hasUserInfo: true,
      userInfoMask: false,
    });
    this.timer(openid, e.detail.avatarUrl, e.detail.nickname);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      theme: app.globalData.theme,
      openid: app.globalData.openid,
      unionid: app.globalData.unionid,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
